import request from 'supertest';
import mongoose from 'mongoose';
import userCenterService from './src/index';
import { User } from './src/models/user';
import { System, SystemType } from './src/models/system';

async function debugAdminLogin() {
  try {
    // 初始化服务
    await userCenterService.init();
    const app = userCenterService.getApp();
    console.log('服务初始化成功');

    // 清理数据
    await User.deleteMany({});
    await System.deleteMany({});

    // 创建超级管理员用户（用作createdBy）
    const tempAdmin = new User({
      username: 'tempadmin',
      password: 'temp123',
      email: 'temp@test.com',
      realName: '临时管理员',
      status: 'active',
      adminLevel: 'super',
      isSuperAdmin: true
    });
    await tempAdmin.save();
    
    // 创建测试系统
    const testSystem = new System({
      systemName: 'Test System',
      systemCode: 'test-system',
      systemType: SystemType.WEB,
      version: '1.0.0',
      description: 'Test system for unit tests',
      status: 'active',
      createdBy: tempAdmin._id
    });
    await testSystem.save();
    console.log('测试系统创建成功');

    // 创建超级管理员用户
    const superAdmin = new User({
      username: 'superadmin',
      password: 'admin123',
      email: 'admin@test.com',
      realName: '超级管理员',
      status: 'active',
      adminLevel: 'super',
      isSuperAdmin: true
    });
    await superAdmin.save();
    console.log('超级管理员用户创建成功');

    // 测试管理员登录
    console.log('开始测试管理员登录...');
    const response = await request(app.callback())
      .post('/api/auth/admin/login')
      .send({
        username: 'superadmin',
        password: 'admin123'
      });

    console.log('响应状态码:', response.status);
    console.log('响应体:', JSON.stringify(response.body, null, 2));

  } catch (error) {
    console.error('调试过程中出错:', error);
  } finally {
    await mongoose.disconnect();
    process.exit(0);
  }
}

debugAdminLogin();
